<?php
/* SVN FILE: $Id: fw24h_functions.php 43 2009-08-25 02:20:20Z phamshantuyet@gmail.com $ */
/**
*
* @author $Author: phamshantuyet@gmail.com $
* @version $Revision: 43 $
* @lastrevision $Date: 2009-08-25 09:20:20 +0700 (Tue, 25 Aug 2009) $
* @modifiedby $LastChangedBy: phamshantuyet@gmail.com $
* @lastmodified $LastChangedDate: 2009-08-25 09:20:20 +0700 (Tue, 25 Aug 2009) $
* @filesource $URL: https://ladybirdphp.googlecode.com/svn/trunk/website/fw24h2/fw24h_functions.php $
*/

/**
 * fw24h_array_walk_recursive()
 * 
 * @param mixed $arr
 * @param mixed $func
 * @return
 */
function fw24h_array_walk_recursive( &$arr, $func ){
	$newArr = array();
	foreach( $arr as $key => $value )
	{
		$arr[ $key ] = ( is_array( $value ) ? fw24h_array_walk_recursive( $value, $func ) : $func( $value ) );
	}
	return $newArr;
}


/**
 * fw24h_replace_bad_char()
 * 
 * @param mixed $p_string
 * @return
 */
function fw24h_replace_bad_char($p_string) {
	if( get_magic_quotes_gpc()) {
		$p_string = stripslashes($p_string);
	}
    $p_string = str_replace('<','&lt;', $p_string);
	$p_string = str_replace('>','&gt;',$p_string);
	$p_string = str_replace('"','&#34;', $p_string);
	$p_string = str_replace("'",'&#39;', $p_string);
	return $p_string;
}

/**
 * fw24h_security_code()
 * 
 * @param integer $p_len
 * @return
 */
function fw24h_security_code( $p_len = 6) {
	return substr( hexdec( md5( microtime())), 2, $p_len);
}

/**
 * fw24h_genID()
 * 
 * @return
 */
function fw24h_genID(){
	$tmp = str_replace(' ','',str_replace('.','',microtime()));	
	return date('YmdHis').$tmp;
}


/**
 * fw24h_file_read_cache()
 * 
 * @param mixed $agr_filename
 * @param mixed $agr_expire
 * @return
 */
function fw24h_file_read_cache( $agr_filename, $agr_expire) {
	//clearstatcache();
	if( file_exists( $agr_filename) && is_readable( $agr_filename) && ($filesize=filesize( $agr_filename)) > 0) {
		if ( time() - filemtime( $agr_filename) > $agr_expire) {
			return false;
		}
		$f_handle = @fopen( $agr_filename, 'rb');
		if( $f_handle) {
			 flock( $f_handle, LOCK_SH);
			//clearstatcache();
			$f_mqr = get_magic_quotes_runtime();
            @set_magic_quotes_runtime(0);
			$f_contents = @fread( $f_handle, $filesize);
			@set_magic_quotes_runtime( $f_mqr);
			@flock( $f_handle, LOCK_UN);
			@fclose( $f_handle);
			return $f_contents;
		}		
	}
	return false;
}

/**
 * fw24h_file_write_cache()
 * 
 * @param mixed $agr_filename
 * @param mixed $agr_contents
 * @return
 */
function fw24h_file_write_cache( $agr_filename, $agr_contents) {
	$f_handle = @fopen( $agr_filename, 'wb');
	if( $f_handle) {
		@flock($f_handle, LOCK_EX);
		fwrite( $f_handle, $agr_contents);
		flock( $f_handle, LOCK_UN); // release the lock
		@fclose( $f_handle);
	}
	return true;
}


/**
 * fw24h_myErrorHandler()
 * 
 * @param mixed $p_errno
 * @param mixed $p_errstr
 * @param mixed $p_errfile
 * @param mixed $p_errlile
 * @return
 */
function fw24h_myErrorHandler( $p_errno, $p_errstr, $p_errfile, $p_errlile) { 
	if( $p_errno == 8  || $p_errno == 2048) { // Notice - bo qua
		return true;
	}
	
	$GLOBALS['_APP_ERROR_'] = true;
	$GLOBALS['QUICKCACHE_ON'] = 0; // ko cache du lieu bi loi

	$f_error_msg = date('Y-m-d H:i:s')."; Err_Code: $p_errno; Err_Str: $p_errstr; Err_File: $p_errfile; Err_Line: $p_errlile\n";
	if( CONST_DISPLAY_ERROR) {
		echo $f_error_msg;
		echo '<PRE>';
		print_r( get_included_files());
	}
	error_log( $f_error_msg, 3, APP_DIR.'/logs/runtime-errors.log');
	
	// hanh dong sau khi co loi
	include APP_DIR.'/views/layouts/error.php';
	
	// ---
	exit(0);
}

/**
 * fw24h_useModel()
 * 
 * @return
 */
function fw24h_useModel() {
	$args = func_get_args();
	
	$p_model_dir = APP_DIR;

	foreach ($args as $arg) {
		$m = strtolower( $arg);
		require_once $p_model_dir.'/modules/'.$m.'/models/'.$m.'_model.php';;
	}
	//include_once FW24H_ROOT.'/'.APP_DIR.'/models/'.strtolower( $p_model).'_model.php';
}

/**
 * fw24h_useVendor()
 * 
 * @return
 */
function fw24h_useVendor() {
	$args = func_get_args();

	$p_vendor_dir = ( defined('USER_VENDOR_DIR')?USER_VENDOR_DIR:APP_DIR);

	foreach ($args as $arg) {
		require_once $p_vendor_dir.'/vendors/'.strtolower( $arg).'.php';;
	}
}

/**
 * fw24h_validate()
 * 
 * @param mixed $p_text
 * @param mixed $p_regular
 * @return
 */
function fw24h_validate( $p_text, $p_regular) {
	if( preg_match( $p_regular, $p_text)) {
		return true;
	}
	return false;
}

/**
 * fw24h_form_validate()
 * 
 * @param mixed $p_form
 * @return
 */
function fw24h_form_validate( $p_form) {
	$f_error = array();
	foreach( $p_form as $v_key=>$v_value) {
		if( $v_value['validate'] == 'none') {
			continue;
		}
		if( !preg_match( '#function:([a-zA-Z0-9\_]+)#', $v_value['validate'], $f_result)) {
			if( !fw24h_validate( $_POST[$v_key], $v_value['validate'])) {
				$f_error[$v_key]['_error'] = $v_value['error'];
			}
		}else{
			if( !$f_result[1]( $_POST[ $v_key])) {
				$f_error[$v_key]['_error'] = $v_value['error'];
			}
		}
		$f_error[$v_key]['value'] = $_POST[$v_key];
	}
	return $f_error;
}

/**
 * fw24h_array_combine()
 * 
 * @param mixed $arr1
 * @param mixed $arr2
 * @return
 */
function fw24h_array_combine( $arr1, $arr2) {
    $out = array();
   
    $arr1 = array_values($arr1);
    $arr2 = array_values($arr2);
   
    foreach($arr1 as $key1 => $value1) {
        $out[(string)$value1] = $arr2[$key1];
    }
   
    return $out;
}

/**
 * fw24h_useComponent()
 * 
 * @return
 */
function fw24h_useComponent() {
	$args = func_get_args();
	foreach ($args as $arg) {
		require_once APP_DIR.'/controllers/components/'.strtolower( $arg).'_component.php';;
	}
}

// log sql command
function fw24h_query( $sql) {
	if( DEBUG_MODE) {
		$f_error_msg = date( 'Y-m-d H:i:s')."; SQL: $sql\n";
		error_log( $f_error_msg, 3, APP_DIR.'/logs/sql.log');
	}
	$rs = mysql_query( $sql) or trigger_error( mysql_error().';;;'.$sql, E_USER_ERROR);
	return $rs;
}

/**
 * Chuyen trang - redirect toi url khac
 *
 * @param string $p_link URL can chuyen toi
 * @return 
 */
function fw24h_url_redirect( $p_link) {
	//@ob_end_clean();
	echo '<script language="JavaScript">location.href="'.$p_link.'"</script><meta http-equiv="Refresh" content="0;URL='.$p_link.'" />';
	exit();
}

/**
 * Lay thong tin ve request hien tai de gui toi trang thong bao loi.
*/
function fw24h_ErrRequest() {
	return 'SERVER_NAME='.$_SERVER['SERVER_NAME'].'&REQUEST_URI='.$_SERVER['REQUEST_URI'].'&SCRIPT_NAME='.$_SERVER['SCRIPT_NAME'].'&REQUEST_TIME='.$_SERVER['REQUEST_TIME'];	
}



// make salt
// thaodx
function fw24h_makeSalt ($minlength=5, $maxlength=6, $useupper=true, $usespecial=false, $usenumbers=true)
{
	$charset = "abcdefghijklmnopqrstuvwxyz";
	if ($useupper) $charset .= "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
	if ($usenumbers) $charset .= "0123456789";
	if ($usespecial) $charset .= "~@#$%^*()_+-={}|]["; // Note: using all special characters this reads: "~!@#$%^&*()_+`-={}|\\]?[\":;'><,./";
	if ($minlength > $maxlength) $length = mt_rand ($maxlength, $minlength);
	else $length = mt_rand ($minlength, $maxlength);
	for ($i=0; $i<$length; $i++) $key .= $charset[(mt_rand(0,(strlen($charset)-1)))];
	return $key;
}
// create password with pass & salt
// thaodx
function fw24h_makePassword($strPass, $strSalt){
	return md5(md5($strPass).$strSalt);
}

function fw24h_isEmail( $strEmail){
	pre( $strEmail);
	$strRegular = '^[A-Za-z0-9_\.\-]+@[A-Za-z0-9_\.\-]+\.';
	$strRegular = $strRegular . '[A-Za-z0-9_\-][A-Za-z0-9_\-]+$';
	if ( !ereg( $strRegular, $strEmail)) {
		return false;
	}    	
	return true;   	
}

/**
	 *  Description	: Check url
	 *  @param 1 	: $url
	 *  @return		: 1/0
	 *  @date		: 2008/08/22
	 *  @author		: Thaodx
	 */
function fw24h_isUrl( $url, $maxlen = 256){
	if( strlen( $url) > $maxlen) {
		return 0;
	}
	if( ereg( '(h{0,1}t{0,2}p{0,1}:{0,1}/{0,1}/{0,1})(w{0,3}\.{0,1})([aA-zZ]+)?\.{1}([aA-zZ]{2,3})(.*)', $url)) {
		return 1;
	}
	return 0;
}

/**
 * Kiem tra du lieu nhap vao co phai la so ten dang nhap hop le, co the them chuoi ky tu hop le
 *
 * @param string $p_username Ten dang nhap can kiem tra
 * @param string $p_allow_chars Chuoi ky tu hop le 
 * @param int $p_min Do rong ngan nhat cua chuoi username, mac dinh la 4
 * @param int $p_max Do dai nhat cua chuoi username, mac dinh la 14
 * @return boolean
 */
function fw24h_isUsername( $p_username, $p_allow_chars='', $p_min=4, $p_max=14) {
	$f_len = strlen( $p_username);
	
	if( $f_len < $p_min || $f_len > $p_max) {
		return false;
	}

	if( !preg_match( "#^[a-zA-Z0-9$p_allow_chars]+$#", $p_username)) {
		return false;
	}
	return true;
}

function fw24h_isPassword( $p_username, $p_allow_chars='', $p_min=4, $p_max=14) {
	return fw24h_isUsername( $p_username, $p_allow_chars, $p_min, $p_max);
}

/**
 * Kiem tra du lieu nhap vao co phai la so dien thoai
 *
 * @param string $p_tel So dien thoai can kiem tra
 * @return boolean
 */
function fw24h_isTelephone( $p_tel) {
	if( preg_match( '#^[+\(\)\. 0-9\,\-]+$#', $p_tel)) {
		return true;
	}
	return false;
}


/**
	 *  Description	: Check $_FILE, type IMGAGE
	 *  @param 1 	: $strName
	 *  @return		: 1/0
	 *  @date		: 2008/08/22
	 *  @author		: Thaodx
	 */		

/**
 * Kiem tra ten file dau vao co hop le, co the them kieu file can kiem tra, format: .jpeg|.jpg|.gif|.pdf
 *
 * @param string $imgfile Ten file can kiem tra
 * @param string $allowExt Cac ext cho phep, mac dinh la .jpeg|.jpg|.gif
 * @param int $max_file_size Kich thuoc toi da cho phep, neu =0 ko kiem tra kich thuoc
 * @param int $errNo Ma loi tra ve
 * @return boolean
 */
function fw24h_checkValidFile( $imgfile,  $allowExt='.jpeg|.jpg|.gif', $max_file_size=0, $errNo='') {
	
	$extension = strtolower( strrchr( $imgfile, '.'));
	
	//check extension
	if( !ereg( $allowExt, $extension)) {
		$errNo = 1;//extension is not allow
		return false;
	}
	//check size
	if( $max_file_size > 0 && file_exists( $imgfile) && filesize( $imgfile) > $max_file_size) {
		$errNo = 2;//size is not allow
		return false;
	}
	return true;
}

// kiem tra kieu du lieu date dau vao - format mm/dd/yyyy, dd/mm/yyyy

/**
 * Kiem tra du lieu dau vao co phai la kieu ngay thang, kieu VN dd/mm/yyyy hoac EN mm/dd/yyyy
 *
 * @param string $p_date Chuoi ngay thang can kiem tra
 * @param string $p_type Kieu ngay thang can kiem tra, mac dinh la EN
 * @return boolean
 */
function FW24H_checkDate( $p_date, $p_type='EN') {
	$p_type = strtoupper( $p_type);
	if( $p_type == 'EN' && ( preg_match( '#^(\d{2})\/(\d{2})\/(\d{4})$#', $p_date, $re) && $p_date == date('m/d/Y', mktime( 0, 0, 0, $re[1], $re[2], $re[3])))) {
		return true;
	}elseif( $p_type == 'VN' && preg_match( '#^(\d{2})\/(\d{2})\/(\d{4})$#', $p_date, $re) && $p_date == date('d/m/Y', mktime( 0, 0, 0, $re[2], $re[1], $re[3]))) {
		return true;
	}
	
	return false;
}


//echo FW24H_checkDate( '22/08/2008', 'VN');

/**
 * Xu ly mang or bien dau vao bang func, mac dinh la func fw24h_replace_bad_char
 *
 * @param mixed $p_var Bien/Mang can duoc xu ly
 * @param string $p_func Ham xu ly bien/mang $p_var
 * @return mixed
 */
function fw24h_cleanInput( $p_var, $p_func='fw24h_replace_bad_char') {
	if( is_array( $p_var)) {
		$newArr = array();
		foreach( $p_var as $key=>$value) {
			$newArr[$key] = ( is_array( $value) ? fw24h_cleanInput( $value, $p_func) : $p_func( $value));
		}
		return $newArr;
	}else{
		return $p_func( $p_var);
	}
}

/**
 * Sinh ra password ngau nhien, mac dinh la 9 ky tu
 *
 * @param int $length
 * @return string password
 */
function fw24h_randomPass($length=9) {
    $vowels = 'aeuy=-BDGHJLMNPQRSTVWXZ';
    $consonants = 'aeuyAEUYbdghjmnpqrstvzBDGHJLMNPQRSTVWXZ23456789@#$%';
    
    $password = '';
    $alt = time() % 2;
    for ($i = 0; $i < $length; $i++) {
        if ($alt == 1) {
            $password .= $consonants[(rand() % strlen($consonants))];
            $alt = 0;
        } else {
            $password .= $vowels[(rand() % strlen($vowels))];
            $alt = 1;
        }
    }
    return $password;
}

function fw24h_base64_url_encode( $input) {
    return strtr( base64_encode( $input), '+/=', '-_,');
}

function fw24h_base64_url_decode( $input) {
    return base64_decode( strtr( $input, '-_,', '+/='));
}

// Get Remote IP Address in PHP
function fw24h_Get_IP_Address() {
	if (!empty($_SERVER['HTTP_CLIENT_IP'])) {   //check ip from share internet
		$ip=$_SERVER['HTTP_CLIENT_IP'];
	}
	elseif (!empty($_SERVER['HTTP_X_FORWARDED_FOR'])) {   //to check ip is pass from proxy
		$ip=$_SERVER['HTTP_X_FORWARDED_FOR'];
	}else {
		$ip=$_SERVER['REMOTE_ADDR'];
	}
	return $ip;
}

function fw24h_load_add_on( $add_on) {
	include_once FW24H_ROOT.'fw24h/add-on/'.$add_on.'.php';
}

//fw24h_load_add_on( 'Cache_Lite/Lite');

/**
 * fw24h_Execute_SQL_Cache()
 * 
 * @param mixed $arg_sql
 * @param integer $agr_expire
 * @param string $arg_path
 * @return
 */
function fw24h_db_query_cache( $arg_sql, $connection, $agr_expire=900, $arg_path='cache/') {
	$v_query_key = $arg_path.'query_'.md5( $arg_sql).'.txt';
	$v_rows = array();
	if( !($v_rs = fw24h_file_read_cache( $v_query_key, $agr_expire))) {
		
		$v_rs = fw24h_db_query( $arg_sql, $connection) or trigger_error( fw24h_db_error( $connection).'!@#'.$arg_sql, E_USER_ERROR);
		while( $v_rs_row = fw24h_db_fetch_assoc( $v_rs)) {
			$v_rows[] = $v_rs_row;
		}
		fw24h_db_free_result( $v_rs);
		fw24h_file_write_cache( $v_query_key, serialize( $v_rows));
	}else{
		$v_rows = unserialize( $v_rs);
	}
	return $v_rows;
}

function pre() {
	echo '<pre>';
	$args = func_get_args();
	foreach ($args as $arg) {
		print_r( $arg);
	}
	echo '</pre>';
}

function fw24h_add_slashes($p_string) {
	if( !get_magic_quotes_gpc()) {
		$p_string = addslashes($p_string);
	}
    return trim( $p_string);
}

